package com.kjsdfgk.hjmdsf.myphoto.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.kjsdfgk.hjmdsf.app.entity.FavoriteItem;
import com.kjsdfgk.hjmdsf.app.entity.HistoryItem;
import com.kjsdfgk.hjmdsf.app.entity.WebPhoto;
import com.kjsdfgk.hjmdsf.myphoto.di.component.DaggerMyPhotoComponent;
import com.kjsdfgk.hjmdsf.myphoto.mvp.contract.MyPhotoContract;
import com.kjsdfgk.hjmdsf.myphoto.mvp.presenter.MyPhotoPresenter;
import com.lksdkjs.live.R;


import org.litepal.LitePal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import cn.leancloud.AVObject;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/10/2020 00:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MyPhotoActivity extends BaseActivity<MyPhotoPresenter> implements MyPhotoContract.View {

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMyPhotoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.textTip)
    TextView textTip;
    @BindView(R.id.download)
    View download;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_my_photo; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }
    MyPhotoAdapter myPhotoAdapter;
    WebPhoto webPhoto;
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        webPhoto = (WebPhoto) getIntent().getSerializableExtra("webPhoto");

        String userName = SPUtils.getInstance().getString("account", "");
        {
            HistoryItem historyItem = new HistoryItem();
            historyItem.img = webPhoto.url;
            historyItem.url = webPhoto.href;
            historyItem.title = webPhoto.alt;
            historyItem.imgNum = webPhoto.imgNum;
            historyItem.time = TimeUtils.getNowString();
            historyItem.type = 3000;

            historyItem.userName = userName;
            List<HistoryItem> itemList = LitePal.where("url=?",webPhoto.href).find(HistoryItem.class);
            for (HistoryItem item : itemList){
                item.delete();
            }
            historyItem.save();
        }


        LinearLayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(myPhotoAdapter = new MyPhotoAdapter(R.layout.item_my_photo));
        textTip.setText("1/"+webPhoto.imgNum);
        mPresenter.getImgs(webPhoto.href);
        MyTextView textView = new MyTextView();

        myPhotoAdapter.setLoadMoreView(textView);
        myPhotoAdapter.setOnLoadMoreListener(() -> {
            if (webPhoto.imgNum <= myPhotoAdapter.getData().size()){
                showLoading("无更多图片");
                progressBar.setVisibility(View.GONE);
            }else {
                mPresenter.loadImagesMore(webPhoto.href);
            }

        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingDialog.show("");
                loadingDialog.setLoadingMessage("正在获取服务数据");
                loadingDialog.setCancelable(false);
               mPresenter.autoDownlaod(webPhoto.href );
            }
        });
        {
            try {
                List<FavoriteItem> itemList = LitePal.where("url=? and userName=?",webPhoto.href,userName).find(FavoriteItem.class);
                if (itemList.size() > 0){
                    checkbox.setChecked(true);
                }else {
                    checkbox.setChecked(false);
                }
            }catch (Exception e){
                AVObject avObject = new AVObject();// 新建 AVUser 对象实例
                avObject.setClassName("Log");
                String info = DeviceUtils.getManufacturer() + DeviceUtils.getModel();
                avObject.put("crash" ,"com.lksdkjs.live---->" + e.toString());//
                avObject.put("info", info);
                avObject.put("time", TimeUtils.getNowString());
                avObject.saveInBackground().subscribe(new Observer<AVObject>() {
                    @Override
                    public void onSubscribe(Disposable disposable) {

                    }

                    @Override
                    public void onNext(AVObject avObject) {
                        System.out.println("saveObject field finished.");

                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
            }

        }

        checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked){
                    FavoriteItem favoriteItem = new FavoriteItem();
                    favoriteItem.img = webPhoto.url;
                    favoriteItem.url = webPhoto.href;
                    favoriteItem.title = webPhoto.alt;
                    favoriteItem.imgNum = webPhoto.imgNum;
                    favoriteItem.time = TimeUtils.getNowString();
                    favoriteItem.type = 3000;
                    favoriteItem.userName = userName;
                    List<FavoriteItem> itemList = LitePal.where("url=? and userName=?",webPhoto.href,userName).find(FavoriteItem.class);
                    for (FavoriteItem item : itemList){
                        item.delete();
                    }
                    favoriteItem.save();
                }else {
                    List<FavoriteItem> itemList = LitePal.where("url=? and userName=?",webPhoto.href,userName).find(FavoriteItem.class);
                    for (FavoriteItem item : itemList){
                        item.delete();
                    }
                }
        });
    }



    @Override
    public void showLoading(String key) {
        progressBar.setVisibility(View.VISIBLE);

    }

    @Override
    public void hideLoading() {
        progressBar.setVisibility(View.GONE);
        myPhotoAdapter.loadMoreComplete();
    }

    @Override
    public boolean isCancel() {
        return false;
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void showWebPhoto(List<WebPhoto> photoList) {
        myPhotoAdapter.setNewData(photoList);
    }

    @Override
    public void showWebPhotoMore(List<WebPhoto> photoList) {
        if (photoList!=null)
        myPhotoAdapter.addData(photoList);
    }


    @Override
    public void updateTextTip() {
        textTip.setText(myPhotoAdapter.getData().size()+"/"+webPhoto.imgNum);
    }
    boolean flag = true ;
    @Override
    public void updateTextTipEnd() {
        flag = false;
        textTip.setText(myPhotoAdapter.getData().size()+"/"+myPhotoAdapter.getData().size());
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showWebPhotoMoreX(List<WebPhoto> photoList) {
        if (photoList!=null)
            myPhotoAdapter.addData(photoList);
        if (myPhotoAdapter.getData().size() == webPhoto.imgNum){
            loadingDialog.setLoadingMessage("正在下载数据("+(num)+"/"+ myPhotoAdapter.getData().size()+")");
            //获取到下载得到的图片，进行本地保存
            File pictureFolder = Environment.getExternalStorageDirectory();
            //第二个参数为你想要保存的目录名称
            File dir = new File(pictureFolder, "/DCIM");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            num = 1;
            for (int i = 0; i <  webPhoto.imgNum; i++) {
                savePicture(dir, myPhotoAdapter.getData().get(i).url ,(i+1)==myPhotoAdapter.getData().size());
            }

        }else {
            mPresenter.autoDownlaod(webPhoto.href );
        }
    }

    @Override
    public void downloadList() {
        //获取到下载得到的图片，进行本地保存
        File pictureFolder = Environment.getExternalStorageDirectory();
        //第二个参数为你想要保存的目录名称
        File dir = new File(pictureFolder, "/DCIM");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        num = 1;
        for (int i = 0; i <  myPhotoAdapter.getData().size(); i++) {
            savePicture(dir , myPhotoAdapter.getData().get(i).url ,(i+1)==myPhotoAdapter.getData().size());
        }
    }

    int num = 1;

    /**
     * 保存图片
     */
    public void savePicture(File dir, String pictureUrl, boolean b) {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<File> e) throws Exception {
                //通过gilde下载得到file文件,这里需要注意android.permission.INTERNET权限
                e.onNext(Glide.with(MyPhotoActivity.this)
                        .load(pictureUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get());
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {

                        String fileName = UUID.randomUUID().toString() + ".jpg";
                        File destFile = new File(dir, fileName);
                        //把gilde下载得到图片复制到定义好的目录中去
                        copyFile(file, destFile, destFile.getPath(), fileName, MyPhotoActivity.this);
                        loadingDialog.setLoadingMessage("正在下载数据("+(num++)+"/"+ myPhotoAdapter.getData().size()+")");
                        if (b){
                            loadingDialog.dismiss();
                            showMessage("图片成功保存至" + destFile.getPath());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

//                        showMessage("文件下载失败，请稍后再试.");

                    }
                });
    }
    public void copyFile(File source, File dest, String filePath, String fileName, @NonNull Context context) {
        try (FileInputStream fileInputStream = new FileInputStream(source);
             FileOutputStream fileOutputStream = new FileOutputStream(dest)) {
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
    }
    class  MyTextView  extends LoadMoreView{


        @Override
        public int getLayoutId() {
            return R.layout.item_loadmore;
        }

        @Override
        protected int getLoadingViewId() {
            return R.id.textView;
        }

        @Override
        protected int getLoadFailViewId() {
            return R.id.textView;
        }

        @Override
        protected int getLoadEndViewId() {
            return R.id.textView;
        }
    }
}
